package com.xusiyan08.service;

import com.xusiyan08.entity.User;
import com.xusiyan08.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public User login(String studentId, String password) {
        Optional<User> user = userRepository.findByStudentIdAndPassword(studentId, password);
        return user.orElse(null);
    }

    public User register(User user) {
        // Check if a user with the same studentId already exists
        Optional<User> existingUser = userRepository.findByStudentId(user.getStudentId());
        if (existingUser.isPresent()) {
            // If user exists, throw an exception
            throw new IllegalArgumentException("学号已存在");
        }
        // If user does not exist, save the new user
        return userRepository.save(user);
    }

    public User getUserById(Long userId) {
        return userRepository.findById(userId).orElse(null);
    }

    public User updateUser(User user) {
        // Find the existing user by ID
        Optional<User> existingUserOptional = userRepository.findById(user.getUserId());

        if (existingUserOptional.isPresent()) {
            User existingUser = existingUserOptional.get();

            // Update only the allowed fields from the incoming user object
            existingUser.setNickname(user.getNickname());
            existingUser.setEmail(user.getEmail());
            existingUser.setPhone(user.getPhone());
            // Optionally update the updated_at timestamp
            existingUser.setUpdatedAt(LocalDateTime.now());

            // Save the updated existing user object
            return userRepository.save(existingUser);
        } else {
            // Handle case where user with the given ID is not found
            // You might want to throw an exception or return null/empty
            throw new RuntimeException("User not found with id: " + user.getUserId());
        }
    }

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }
   public User getUserByStudentId(String studentId) {
        return userRepository.findByStudentId(studentId).orElse(null);
    }
    public void deleteUser(Long userId) {
        userRepository.deleteById(userId);
    }
}